package com.atguigu.yygh.hosp.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.model.hosp.HospitalSet;
import com.atguigu.yygh.vo.hosp.HospitalSetQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author 杨林
 * @create 2022-10-30 17:28 星期日
 * description:
 */
@Api(description = "医院设置接口")
//@CrossOrigin //跨域  //通过网关解决跨域问题
@RestController
@RequestMapping("/admin/hosp/hospitalSet")
public class HospitalSetController {

    @Autowired
    private HospitalSetService hospitalSetService;

    //查询所有医院设置
    @GetMapping("/findAll")
    @ApiOperation(value = "医院设置列表")
    public R findAll(){
        List<HospitalSet> list = hospitalSetService.list();
//        try {
//            int i = 10/0;
//        } catch (Exception e) {
//            throw new YyghException(20001,"这是自定义异常");
//        }
        return R.ok().data("list",list);
    }

    //逻辑删除
    @ApiOperation(value = "根据id医院设置（逻辑删除）")
    @DeleteMapping("{id}")
    public R deleted(@ApiParam(name = "id",value = "医院设置主键",required = true) @PathVariable Long id){
        return hospitalSetService.removeById(id) ? R.ok() : R.error();
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("{page}/{limit}")
    public R pageList(@ApiParam(name = "page",value = "当前页码",required = true)
                          @PathVariable Long page,
                      @ApiParam(name = "limit",value = "每页条数",required = true)
                      @PathVariable Long limit){
//        Page<HospitalSet> pageParam = new Page<>(page, limit);
//        Page<HospitalSet> records = hospitalSetService.page(pageParam, null);
//        long total = pageParam.getTotal();
//        return R.ok().data("total",total).data("rows",records);
        Map<String, Object> map = hospitalSetService.selectPage(page, limit);
        return R.ok().data(map);
    }

    @ApiOperation(value = "分页条件医院设置列表")
    @PostMapping("{page}/{limit}")
    public R pageQuery(@ApiParam(name = "page",value = "当前页码",required = true)
                      @PathVariable Long page,
                      @ApiParam(name = "limit",value = "每页条数",required = true)
                      @PathVariable Long limit,
                      @ApiParam(name = "hospitalSetQueryVo",value = "查询对象",required = true)
                      @RequestBody HospitalSetQueryVo hospitalSetQueryVo){
        Map<String, Object> map = hospitalSetService.selectPageQuery(page, limit, hospitalSetQueryVo);
        return R.ok().data(map);

    }

    /**
     * 保存医院设置
     */
    @ApiOperation(value = "新增的医院设置")
    @PostMapping("/saveHospSet")
    public R save(@ApiParam(name = "hospitalSet",value = "新增",required = true)
                      @RequestBody HospitalSet hospitalSet){

        //检查医院是否存在（判断医院编号是否存在）
        String hoscode = hospitalSet.getHoscode();
        //对hoscode做非空校验
        if (StringUtils.isEmpty(hoscode)){
            return R.error().message("医院编号不能为空");
        }
        //根据hoscode查询
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hoscode", hoscode);
        queryWrapper.last("OR (is_deleted = 1 and hoscode = " + hoscode + ")");
        int count = hospitalSetService.count(queryWrapper);
        if (count > 0){
            return R.error().message("该医院已经开通医院设置");
        }

        //为新增的医院设置设置状态 0：表示可用 1：表示不可用
        hospitalSet.setStatus(1);

        //为新增的医院设置设置签名
        //Random random = new Random();
        //hospitalSet.setSignKey(MD5);
        boolean save = hospitalSetService.save(hospitalSet);
        return save ? R.ok() : R.error();
    }

    /**
     * 根据id查询医院设置
     */
    @ApiOperation(value = "根据id查询医院设置")
    @GetMapping("getHospSet/{id}")
    public R selectHospById(@ApiParam(name = "id",value = "查询的id",required = true)
                                @PathVariable Long id){
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        return R.ok().data("item",hospitalSet);
    }

    /**
     * 根据id修改
     */
    @ApiOperation("根据id修改医院设置")
    @PostMapping("updateHospSet")
    public R updateById(@ApiParam(name = "hospitalSet" ,value = "修改后的医院设置",required = true)
            @RequestBody HospitalSet hospitalSet){
        //对id进行非空校验
        Long id = hospitalSet.getId();
        if(StringUtils.isEmpty(id)){
            return R.error().message("医院id不能为空");
        }

        //防止修改hoscode的值
        hospitalSet.setHoscode(null);
        boolean b = hospitalSetService.updateById(hospitalSet);
        return b ? R.ok() : R.error();
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/batchRemove")
    public R deleteByIds(@RequestBody List<Long> idList){
        if (idList == null || idList.size() == 0){
            return R.error().message("请传递参数");
        }

        boolean isDeleted = hospitalSetService.removeByIds(idList);
        return isDeleted ? R.ok():R.error();
    }

    /**
     * 医院设置锁定和解锁
     */
    @PutMapping("lockHospitalSet/{id}/{status}")
    public R lockHospitalSet(@PathVariable Long id,@PathVariable Integer status){

        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(status)){
            return R.error().message("参数不能为空");
        }

        HospitalSet hospitalSet = hospitalSetService.getById(id);
        if (status != 0 && status != 1){
            return R.error().message("status只能为0或者1");
        }

        hospitalSet.setStatus(status);
        boolean update = hospitalSetService.updateById(hospitalSet);
        return update ? R.ok():R.error();
    }
}
